package com.ruoyi.quartz.task;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DayUtils;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.feike.domain.DealercodeContractFiling;
import com.ruoyi.feike.domain.HDealerDm;
import com.ruoyi.feike.domain.LimitActiveProposal;
import com.ruoyi.feike.domain.NewSumKeep;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.ContractRecordMapper;
import com.ruoyi.feike.mapper.HDealerDmMapper;
import com.ruoyi.feike.mapper.NewSumKeepMapper;
import com.ruoyi.feike.service.ILimitActiveProposalService;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask
{

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取 ‘
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private NewSumKeepMapper newSumKeepMapper;

    @Autowired
    private HDealerDmMapper dealerDmMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ILimitActiveProposalService limitActiveProposalService;

    @Autowired
    private ContractRecordMapper contractRecordMapper;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() throws IOException {
        System.out.println("执行保险到期邮件发送方法");
        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(new Date());
        ca.add(Calendar.DAY_OF_MONTH, 30);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String futDate = simpleDateFormat.format(ca.getTime());
        Date expiryDate = null;
        try {
            expiryDate = simpleDateFormat.parse(futDate);
        }catch (Exception e) {
            e.printStackTrace();
        }
        if(expiryDate!=null){
            NewSumKeep newSumKeep = new NewSumKeep();
            newSumKeep.setExpiryDate(expiryDate);
            List<NewSumKeep> newSumKeeps = newSumKeepMapper.selectNewSumKeepList5(newSumKeep);
            if(newSumKeeps!=null && newSumKeeps.size()>0){
                for (NewSumKeep sumKeep : newSumKeeps) {
                    HDealerDm hDealerDm = dealerDmMapper.selectHDealerDmByDealerName(sumKeep.getDealerName());
                    if(hDealerDm!=null && hDealerDm.getDmName()!=null){
                        SysUser sysUser = sysUserMapper.selectUserByNickName(hDealerDm.getDmName());
                        if(sysUser!=null){
                            sendMailByEmailInfo(sysUser,sumKeep.getDealerName(),sumKeep.getSector(),false);
                        }

                    }

                }
            }
        }

    }

    public void sendMailByEmailInfo(SysUser sysUser,String dealerName,String sector ,boolean flag) throws IOException {
        if(isSendEmal!=null && isSendEmal.equals("true")) {
            String ln = "<br>";
            String content = msg + ln + "经销商名称:" + dealerName + ln + "经销商品牌：" + sector +"  30天后将过期,请关注!"+ ln + "网站链接:" + "<a href ='" + url + "'>点此登录</a>";
            // 获取邮箱
            String email = sysUser.getEmail();
            if (!StringUtil.isEmpty(email)) {
                try {
                    // 测试文本邮件发送（无附件）
                    String to = email;
                    String title = "保险即将过期邮件提醒";

                    //带附件方式调用
                    new EmailUtil(from, mailSender).sendMessageCarryFiles(to, title, content, null);
                    // return AjaxResult.success();
                } catch (Exception e) {

                }
            }
        }
    }

    public void sendInsureNotice() throws IOException {
        System.out.println("执行费率更新通知op购买保险");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        NewSumKeep newSumKeep = new NewSumKeep();
        List<NewSumKeep> sumKeeps = new ArrayList<>();
        List<NewSumKeep> newSumKeeps = newSumKeepMapper.selectNewSumKeepList6(newSumKeep);
        if(newSumKeeps!=null && newSumKeeps.size()>0){
            for (NewSumKeep sumKeep : newSumKeeps) {
                //计算新费率需要的保费
                String StartStr = sdf.format(sumKeep.getEffectiveDate());
                String endStr = sdf.format(sumKeep.getExpiryDate());
                Map<String, Object> rate = newSumKeepMapper.getRate(sumKeep.getSector());
                String oldMinRate = rate.get("oldMinRate").toString();
                String oldMaxRate = rate.get("oldMaxRate").toString();
                String minRate = rate.get("minRate").toString();
                String maxRate = rate.get("maxRate").toString();
                BigDecimal dayAmt = new BigDecimal(0);
                BigDecimal newSumDay = new BigDecimal(0);
                boolean run =false;
                List<String> yearList = DayUtils.getYearBetweenDate(StartStr, endStr);
                List<String> runList = new ArrayList<>();
                for (String s : yearList) {
                    runList.add(s+"-02-29");
                }
                if(runList.size()>0){
                    List<String> everyday = DayUtils.getEveryday(StartStr, endStr);
                    for (String s : runList) {
                        if(everyday.contains(s) && !endStr.equals(s)){
                            run = true;
                            System.out.println("闰年");
                            break;
                        }
                    }
                }
                //匹配
                try {
                    if(sumKeep.getPlanRate().equals(oldMinRate)){
                        //新费率为小
                        BigDecimal multiply = new BigDecimal(sumKeep.getSum()).multiply(new BigDecimal(minRate)).setScale(10,BigDecimal.ROUND_HALF_UP);
                        if(run){
                            dayAmt = multiply.divide(new BigDecimal(366),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                        }else{
                            dayAmt = multiply.divide(new BigDecimal(365),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                        }
                    }else if(sumKeep.getPlanRate().equals(oldMaxRate)){
                        //新费率为大
                        BigDecimal multiply = new BigDecimal(sumKeep.getSum()).multiply(new BigDecimal(maxRate)).setScale(10,BigDecimal.ROUND_HALF_UP);
                        if(run){
                            dayAmt = multiply.divide(new BigDecimal(366),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                        }else{
                            dayAmt = multiply.divide(new BigDecimal(365),BigDecimal.ROUND_HALF_UP).setScale(10,BigDecimal.ROUND_HALF_UP);
                        }
                    }else{
                        System.out.println("保险数据费率不匹配,数据id为:"+sumKeep.getId());
                    }
                    int i2 = DayUtils.daysBetween(StartStr, endStr);
                    newSumDay = dayAmt.multiply(new BigDecimal(i2+1)).setScale(2, BigDecimal.ROUND_HALF_UP);
                }catch (Exception e){
                    e.printStackTrace();
                    break;
                }
                NewSumKeep newSumKeepTemp = new NewSumKeep();
                newSumKeepTemp.setDealerName(sumKeep.getDealerName());
                newSumKeepTemp.setSector(sumKeep.getSector());
                newSumKeepTemp.setSum(sumKeep.getSum());
                newSumKeepTemp.setEffectiveDate(sumKeep.getEffectiveDate());
                newSumKeepTemp.setExpiryDate(sumKeep.getExpiryDate());
                newSumKeepTemp.setPremium(newSumDay.toString());
                sumKeeps.add(newSumKeepTemp);
            }
        }
        if(sumKeeps!=null && sumKeeps.size()>0){
            ArrayList<String> groups = new ArrayList<>();
            groups.add("dm");
            groups.add("op");
            SysPostMapper sysPostMapper = SpringUtils.getBean(SysPostMapper.class);
            for (String group : groups) {
                System.out.println("groupId==" + group);
                // 根据组查对应组成员id，在查到对应的用户对象信息
                List<SysUser> userList = sysPostMapper.selectUserListByPostCode(group);
                System.out.println("userList==" + userList.toString());
                if (userList != null && userList.size() > 0) {
                    for (SysUser sysUser : userList) {
                        // 调用发送邮件方法
                        try {
                            sendMailByEmailInfo(sysUser,sumKeeps);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public void sendMailByEmailInfo(SysUser user,List<NewSumKeep> sumKeeps) {
        try {
            StringBuilder contentStr = new StringBuilder();
            StringBuilder content = new StringBuilder("<html><head></head><body><h3>保险超出有效期信息</h3>");
            content.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size:16px;\">");
            content.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>经销商名称</th><th>品牌</th><th>保额</th><th>保险起始日</th><th>保险到期日</th><th>保费</th></tr>");
            if(sumKeeps!=null && sumKeeps.size()>0){
                for (NewSumKeep keep : sumKeeps) {
                    content.append("<tr>");
                    content.append("<td>" + keep.getDealerName() + "</td>"); //第一列
                    content.append("<td>" + keep.getSector() + "</td>"); //第二列
                    DecimalFormat df = new DecimalFormat("#,###");
                    BigDecimal bigDecimal = new BigDecimal(keep.getSum());
                    String amt =  NumberFormat.getNumberInstance().format(bigDecimal);
                    content.append("<td>" + amt + "</td>"); //第三列
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String StartDate = sdf.format(keep.getEffectiveDate());
                    String endDate = sdf.format(keep.getExpiryDate());
                    content.append("<td>" + StartDate + "</td>"); //第四列
                    content.append("<td>" + endDate + "</td>"); //第五列
                    content.append("<td>" + keep.getPremium() + "</td>"); //第六列
                    content.append("</tr>");

                }
            }
            content.append("</table>");
            content.append("</body></html>");
            contentStr.append(msg);
            contentStr.append(content);
            // 测试文本邮件发送（无附件）
            String to = user.getEmail();
            if(!StringUtil.isEmpty(to)){
                System.out.println("发送任务到"+ to);
                String title = "保险超出有效期信息(费率更新)";
                //带附件方式调用
                JavaMailSender bean = SpringUtils.getBean(JavaMailSender.class);
                new EmailUtil(from, bean).sendMessageCarryFiles(to, title, contentStr.toString(), null);
                // return AjaxResult.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sysCheck() throws IOException {
        System.out.println("执行sysCheck");
        try{
            List<org.activiti.engine.task.Task> listTaskXs = taskService.createTaskQuery()
                    .taskCandidateOrAssigned("admin")
                    .list();
            if(listTaskXs!=null&&listTaskXs.size()>0){
                for (Task task1 : listTaskXs) {
                    List<HistoricProcessInstance> list1 = historyService.createHistoricProcessInstanceQuery().processInstanceId(task1.getProcessInstanceId()).list();
                    if (CollectionUtil.isNotEmpty(list1)) {
                        String  businessKey = list1.get(0).getBusinessKey();
                        System.out.println(task1.getName());
                        System.out.println(businessKey);

                        LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
                        limitActiveProposal.setInstanceId(businessKey);
                        List<LimitActiveProposal> limitActiveProposals = limitActiveProposalService.selectLimitActiveProposalList(limitActiveProposal);
                        if(limitActiveProposals!=null && limitActiveProposals.size()>0){

                            ArrayList<String> booleans = new ArrayList<>();
                            for (LimitActiveProposal activeProposal : limitActiveProposals) {
                                if (activeProposal.getIsReplace() == 0 && StringUtils.isNotEmpty(activeProposal.getProposalActiveLimit()) && !activeProposal.getProposalActiveLimit().equals("0")) {
                                    //查询合同信息
                                    String flag = "false";
                                    ContractRecord contractRecord = new ContractRecord();
                                    contractRecord.setDealername(activeProposal.getDealerName());
                                    contractRecord.setSector(activeProposal.getSector());
                                    contractRecord.setLimitType(activeProposal.getLimitType());
                                    contractRecord.setContracttype("试乘试驾车抵押合同（E已更改）");
                                    List<ContractRecord> contractRecords = null;
                                    if(activeProposal.getLimitType().equals("PART")){
                                        contractRecord.setLimitType(null);
                                        contractRecords = contractRecordMapper.selectContractRecordListRecentlyEffectiveDate2ByPart(contractRecord);
                                    }else{
                                        contractRecords = contractRecordMapper.selectContractRecordListRecentlyEffectiveDate2(contractRecord);
                                    }
                                    if(contractRecords ==null || contractRecords.size() ==0 ){
                                        booleans.add(flag);
                                        continue;
                                    }
                                    if (StringUtils.isNotEmpty(contractRecords.get(0).getFacilityamount())) {
                                        Long  facilityamount = Long.valueOf(contractRecords.get(0).getFacilityamount());
                                        long l = new DecimalFormat().parse(activeProposal.getProposalActiveLimit()).longValue();
                                        System.out.println("xxxx"+facilityamount);
                                        System.out.println("zzzz"+l);
                                        if(activeProposal.getLimitType().equals("PART")){
                                            facilityamount = Long.valueOf(contractRecords.get(0).getPartsAmount());
                                        }
                                        if (facilityamount >= l) {
                                            System.out.println("校验一通过");
                                            //校验一通过
                                            if (StringUtils.isNotNull(contractRecords.get(0).getExpirydate())) {
                                                Date expirydate = contractRecords.get(0).getExpirydate();
                                                Date proposedEnd = activeProposal.getProposedEnd();
                                                if (expirydate.compareTo(proposedEnd) >= 0) {
                                                    System.out.println("校验二通过");
                                                    //校验二通过
                                                    if(activeProposal.getLimitType().equals("TEMP")){
                                                        flag = "true";
                                                    }else{
                                                        if(activeProposal.getLimitType().equals("PART")){
                                                            String depositStr = contractRecords.get(0).getPartsDepositRatio().replace("%", "");
                                                            Double deposit = Double.valueOf(depositStr);
                                                            String cashDepositStr = activeProposal.getApprovedCashDeposit().replace("%", "");
                                                            Double cashDeposit = Double.valueOf(cashDepositStr);
                                                            System.out.println("aaaa"+deposit);
                                                            System.out.println("bbbb"+cashDeposit);
                                                            if (deposit <= cashDeposit) {
                                                                System.out.println("校验三通过");
                                                                //校验三通过
                                                                Date effectiveDate = contractRecords.get(0).getEffectivedate();
                                                                if (effectiveDate != null) {
                                                                    //校验四通过
                                                                    flag = "true";
                                                                }
                                                            }
                                                        }else{
                                                            if (StringUtils.isNotEmpty(contractRecords.get(0).getDeposit())) {
                                                                String depositStr = contractRecords.get(0).getDeposit().replace("%", "");
                                                                Double deposit = Double.valueOf(depositStr);
                                                                String cashDepositStr = activeProposal.getApprovedCashDeposit().replace("%", "");
                                                                Double cashDeposit = Double.valueOf(cashDepositStr);
                                                                System.out.println("aaaa"+deposit);
                                                                System.out.println("bbbb"+cashDeposit);
                                                                if (deposit <= cashDeposit) {
                                                                    //校验三通过
                                                                    Date effectiveDate = contractRecords.get(0).getEffectivedate();
                                                                    if (effectiveDate != null) {
                                                                        //校验四通过
                                                                        flag = "true";
                                                                    }
                                                                }
                                                            }
                                                        }

                                                    }

                                                }
                                            }
                                        }
                                    }
                                    booleans.add(flag);
                                }else{
                                    /*
                                     activeProposal.setContractStatus("");
                                     limitActiveProposalService.updateLimitActiveProposal(activeProposal);
                                    */
                                }
                            }
                            //判断是否全部通过
                            if(!booleans.contains("false")){
                                System.out.println("下一个流程");
                                Authentication.setAuthenticatedUserId("1");
                                HashMap<String, Object> variables1 = new HashMap<String, Object>();
                                variables1.put("FormProperty_2gu4s9q",0);
                                taskService.complete(task1.getId(),variables1);
                                ActTaskServiceImpl actTaskService = SpringUtils.getBean(ActTaskServiceImpl.class);
                                List<String> uws = sysUserMapper.getuwNamesByPostCode("underwriter");
                                for (String uw : uws) {
                                    actTaskService.sendMailByEmailInfo(sysUserMapper.selectUserByUserName(uw),businessKey,false,"UW-Requester");
                                }
                                LimitActiveProposal limitActiveProposalUpate = new LimitActiveProposal();
                                limitActiveProposalUpate.setInstanceId(businessKey);
                                List<LimitActiveProposal> limitActiveProposalsUpdate = limitActiveProposalService.selectLimitActiveProposalList(limitActiveProposalUpate);
                                for (LimitActiveProposal activeProposal : limitActiveProposalsUpdate) {
                                    ContractRecord contractRecord = new ContractRecord();
                                    contractRecord.setDealername(activeProposal.getDealerName());
                                    contractRecord.setSector(activeProposal.getSector());
                                    contractRecord.setLimitType(activeProposal.getLimitType());
                                    contractRecord.setContracttype("试乘试驾车抵押合同（E已更改）");
                                    List<ContractRecord> contractRecords = null;
                                    if(activeProposal.getLimitType().equals("PART")){
                                        contractRecord.setLimitType(null);
                                        contractRecords = contractRecordMapper.selectContractRecordListRecentlyEffectiveDate2ByPart(contractRecord);
                                    }else{
                                        contractRecords = contractRecordMapper.selectContractRecordListRecentlyEffectiveDate2(contractRecord);
                                    }
                                    if(contractRecords!=null && contractRecords.size()>0 ){
                                        activeProposal.setContractStatus("已签回");
                                        if(contractRecords.get(0)!= null ){
                                            activeProposal.setContractHyperlink(contractRecords.get(0).getFileUrl());
                                        }
                                        if (activeProposal.getIsReplace() == 1) {
                                            activeProposal.setContractStatus("");
                                        }
                                        if(contractRecords.get(0)!=null && activeProposal.getLimitType().equals("PART")){
                                            activeProposal.setContractFacilityAmount(contractRecords.get(0).getPartsAmount());
                                        }else{
                                            activeProposal.setContractFacilityAmount(contractRecords.get(0).getFacilityamount());
                                        }
                                        if(contractRecords.get(0)!=null){
                                            activeProposal.setContractExpireDate(contractRecords.get(0).getExpirydate());
                                        }
                                        if(contractRecords.get(0)!=null && activeProposal.getLimitType().equals("PART")){
                                            activeProposal.setContractDepositRatio(contractRecords.get(0).getPartsDepositRatio());
                                        }else{
                                            activeProposal.setContractDepositRatio(contractRecords.get(0).getDeposit());
                                        }
                                        limitActiveProposalService.updateLimitActiveProposal(activeProposal);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw  new BaseException("执行定时任务异常!,请检查");
        }
    }
}
